package com.jvmoutofmemory.octopus.ui;

import com.jvmoutofmemory.octopus.model.FileModel;

import javax.swing.table.DefaultTableModel;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class OctopusTableModel extends DefaultTableModel {

    private List<FileModel> fileModels = new ArrayList<>();

    public void initialize() {
        fileModels = new ArrayList<>();
        this.setColumnIdentifiers(FileModel.titles);
    }

    public FileModel getFileModel(int row) {
        return fileModels.get(row);
    }

    public List<FileModel> getFileModels() {
        return fileModels;
    }

    public void addFile(File file) {
        if (!containsFile(file)) {
            fileModels.add(new FileModel(file));
        }
    }

    public void clearAllFiles() {
        fileModels.clear();
    }

    public boolean hasUnprintedFiles() {
        if (fileModels == null || fileModels.size() == 0) {
            return false;
        }

        for (FileModel model : fileModels) {
            if (model.getStatusCode() == FileModel.status_unprint) {
                return true;
            }
        }

        return false;
    }

    public boolean containsFile(File file) {
        return containsFile(file.getAbsolutePath());
    }

    public boolean containsFile(String path) {
        if (path == null) {
            return true;
        }

        for (FileModel model : fileModels) {
            if (path.equals(model.getFilepath())) {
                return true;
            }
        }

        return false;
    }

    public void sort() {
        /*if (fileModels == null || fileModels.size() == 0) {
            return;
        }

        fileModels.sort(new Comparator<FileModel>() {
            @Override
            public int compare(FileModel o1, FileModel o2) {
                if (o1.getStatusCode() != o2.getStatusCode()) {
                    return Integer.compare(o2.getStatusCode(), o1.getStatusCode());
                }

                return o1.getName().compareTo(o2.getName());
            }
        });*/
    }

    @Override
    public int getRowCount() {
        return fileModels == null ? 0 : fileModels.size();
    }

    @Override
    public int getColumnCount() {
        return FileModel.titles.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if (rowIndex < fileModels.size() && columnIndex < FileModel.titles.length) {
            return fileModels.get(rowIndex).toRowData()[columnIndex];
        }
        return null;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }
}
